/*
 * Lights-Out Player implementation
 */
#include "lib/lightsout_util.h"

int main(int argc, char* argv[]){
    //check arguments of cmd
    if(argc != 2){
        fprintf(stderr, "Usage: loplayer <board name>\n");
        return 1;
    }
    char *board_filename = argv[1];
    ba_ht_elem start = xmalloc(sizeof(struct ba_ht_elem_base));
    uint8_t width = 0;
	uint8_t height = 0;
    if (!file_read(board_filename, &(start->ba), &width, &height)) {
        free(start);
        fprintf(stderr, "Input file format wrong!\n");
        return 1;
    }
    printf("Welcome to lights out player!\n");
    int flag = 1;
    int sol_row = 0, sol_col = 0;
    bitarray sol_bitarray = start->ba;
    while(flag == 1){
        if(!bitarray_equal(sol_bitarray, bitarray_new())){
            print_board(sol_bitarray, width, height);
            printf("Please input touch position, format: <row:col>\n");
            printf("Position range: 0 <= row < %d, 0 <= col < %d\n", height, width);
            printf("Input other characters to quit!\n");
            char c;
            for(int i = 3; i > 0 && flag == 1; --i){
                c = getchar();
                //printf("%d",c);//debug
                switch(i){
                    case 3:
                        if(!('0' <= c && c <= '9')){
                            flag = 0;
                        }
                        else{
                            sol_row = c - '0';
                            
                        }
                        break;
                    case 2:
                        if(c != ':'){
                            flag = 0;
                        }
                        break;
                    case 1:
                        if(!('0' <= c && c <= '9')){
                            flag = 0;
                        }
                        else{
                            sol_col = c - '0';
                        }
                        break;
                }
            }
            getchar();//get \n
            if(flag){
                if(!is_valid_pos(sol_row, sol_col, width, height)){
                    fprintf(stderr, "Input position out of range!\n");
                    return -1;
                }
                ba_ht_elem sol = xmalloc(sizeof(struct ba_ht_elem_base));
                sol->ba = sol_bitarray;
                printf("Flipping %d:%d\n", sol_row, sol_col);
                uint8_t index = get_index(sol_row, sol_col, width, height);
                sol_bitarray = press_button(sol, index, sol_row, sol_col, width, height);
                free(sol);
            }
        }
        else{
            printf("All lights off, you have won the game!\n");
            flag = 0;
        }
    }
    return 0;
}